<template>
  <label class="m-checkbox" :class="{'is-checked':isChecked,'is-disabled':disabled}">
    <span class="m-checkbox__input" :class="{'is-checked':isChecked}">
      <span class="m-checkbox__inner"></span>
      <input
      class="m-checkbox__checkbox"
      type="checkbox"
      :value="value"
      :disabled="disabled"
      v-model="model">
    </span>
    <span class="m-checkbox__label">
      <slot>
        {{label}}
      </slot>
    </span>
  </label>
</template>

<script>
export default {
  name: 'Checkbox',
  props: {
    value: null,
    label: String,
    disabled: Boolean
  },
  data() {
    return {
      isGroup: false
    }
  },
  created() {
    this.isGroup = this.isCheckboxGroup()
  },
  computed: {
    isChecked() {
      if (this.isGroup) {
        return this._checkboxGroup.value.includes(this.value)
      } else {
        return this.value
      }
    },
    model: {
      get() {
        return this.isGroup ? this._checkboxGroup.value : this.value
      },
      set(val) {
        this.isGroup
          ? this._checkboxGroup.dispatchChange(val)
          : this.emitChange(val)
      }
    }
  },
  methods: {
    emitChange(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    },
    isCheckboxGroup() {
      let temp = this.$parent

      while (temp) {
        if (temp.$options.componentName === 'CheckboxGroup') {
          this._checkboxGroup = temp
          return true
        }
        temp = temp.$parent
      }
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
$size: 14px;
$colorDisbaled: #c0c4cc;
.m-checkbox {
  display: inline-block;
  font-size: 14px;
  cursor: pointer;

  &.is-disabled {
    cursor: not-allowed;
    color: $colorDisbaled;
  }

  &__input {
    position: relative;
    &.is-checked {
      .m-checkbox__inner {
        background-image: url('../assets/check.png');
      }
    }
  }
  &__checkbox {
    position: absolute;
    z-index: -1;
    width: 0;
    height: 0;
    opacity: 0;
  }

  &__inner {
    width: $size;
    height: $size;
    display: inline-block;
    background-image: url('../assets/icon-checkbox.png');
    background-size: 100%;
    vertical-align: middle;
    line-height: 1;
  }

  &__label {
    vertical-align: middle;
    line-height: 1;
  }
}
</style>
